import { Vector2 } from "three";

/**
 *  可以使得DOM拥有拖拽Y轴的能力
 * @param resizeTarget {HTMLDivElement} 调整的容器
 * @param resizeBar {HTMLElement} 拖拽柄
 */
export default function (resizeTarget, resizeBar) {
  /**
   * 纪录容器大小
   * @type {Vector2}
   */
  let containerSize = new Vector2(resizeTarget.offsetWidth, resizeTarget.offsetHeight);
  let startPos = new Vector2();
  adjustStyle(resizeTarget, resizeBar);

  /**
   * 鼠标拖拽移动时触发的事件
   * @param e {MouseEvent}
   */
  function mousemoveEventHandler(e) {
    let curPos = new Vector2(e.pageX, e.pageY);
    let distanceVec = curPos.sub(startPos);
    resizeTarget.style.height = containerSize.y + distanceVec.y + "px";
  }

  /**
   * 鼠标按下的事件监听
   * @param e {MouseEvent}
   */
  function mousedownEventHandler(e) {
    startPos.x = e.pageX;
    startPos.y = e.pageY;
    document.addEventListener("mousemove", mousemoveEventHandler);
    document.addEventListener("mouseup", mouseupEventHandler);
  }

  /**
   * 鼠标抬起的事件
   * @param e {MouseEvent}
   */
  function mouseupEventHandler(e) {
    document.removeEventListener("mousemove", mousemoveEventHandler);
    containerSize.x = resizeTarget.offsetWidth;
    containerSize.y = resizeTarget.offsetHeight;
  }

  resizeBar.addEventListener("mousedown", mousedownEventHandler);
}

/**
 *  调整元素的样式
 * @param resizeTarget {HTMLElement}
 * @param resizeBar {HTMLElement}
 */
function adjustStyle(resizeTarget, resizeBar) {
  resizeBar.style.cursor = "ns-resize";
  resizeBar.style.height = "5px";
  resizeTarget.style.height = `${resizeTarget.offsetHeight}px`;
}